package util::parse;

require Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(parse parse_log parse_apache);

use strict;
use warnings;

sub parse
{
	my $config_file = shift;
	my %config;
	open my $fh_conf, "<", "$config_file" or die "$!\n";
	while(my $line = <$fh_conf>)
	{
		next if $line =~ m/^#/ or $line =~ m/^$/;
		if ($line =~ m/^\[(\w+)\]/)
		{
			$a = $1;
			$config{$a} = {} unless exists $config{$a};
		}
		elsif ($line =~ m/(\w+):\s+(\S+)?/)
		{
			${ config{$a} }{$1} = $2; 
		}
	}
	close $fh_conf;
	return \%config;
}


sub parse_log
{
	use Encode;
	my $line = shift;
	my @lines;
	my @i = split m/\"/, $line;
	my @logs = split m/\s+/, $i[0];
	return 0 if $logs[5] =~ m/-/;
	$i[1]    =~ s/^(?:GET|POST)\s+?(.*)HTTP\/1\.[10]$/$1/;
#	$i[2]    =~ s/^\s+(\d{1,3})\s+\d+/$1/;
	$i[2]    =~ s/^\s+(\d{1,3})\s+(\d+)/$1 $2/;
    my @j    = split m/\s+/, $i[2];
	$logs[4] =~ s/:\d+$//;
	$logs[5] =~ s/^.*?://;
	$logs[7] =~ s/\s//g;
	$logs[0] = 'null' if $logs[0] =~ m/-/;
	$logs[1] = 0 if $logs[1] =~ m/-/;
	push @lines, $logs[0], $logs[1], $logs[4], $logs[5], $logs[2],
                    encode("utf8",$logs[7]), encode( "utf8", $i[1] ),
                    $j[0],$j[1],
                    encode( "utf8", $i[3] ),
                    encode( "utf8", $i[5] );
    return @lines;
}

sub parse_apache
{
	use Encode;
	my $line = shift;
	my @lines;
	my @i = split m/\"/, $line;
	my @logs = split m/\s+/, $i[0];
	$logs[2] =~ s/^.*?://;
	$i[1]    =~ s/^(?:GET|POST)\s+?(.*)HTTP\/1\.[10]$/$1/;
	$i[2]    =~ s/^\s+(\d{1,3})\s+\d+/$1/;
	push @lines, $logs[0] / 1000 ,$logs[2],$logs[1],$logs[4],$i[1],$i[2],$i[3],$i[5];
	return \@lines;
}

1;
